#include "buddylist.h"
#include "ui_buddylist.h"
#include "addcontact.h"
#include <QString>
#include <QApplication>
#include <QCloseEvent>
#include <QtGui>



BuddyList::BuddyList(QWidget *parent) :
        QDialog(parent),
        m_ui(new Ui::BuddyList)
{
    m_ui->setupUi(this);
    userName = ClientHandler::clientHandlerInstance()->getUsername();
    //ClientHandler::clientHandlerInstance()->getBuddies();

    this->setWindowTitle("MyChat");
    m_ui->theUser->setText(userName);
    m_ui->theUser->show();

    // signal and slot connections
    connect(m_ui->addContact, SIGNAL(clicked()), this, SLOT(clickedAddContact()));

    connect(m_ui->statusBox,SIGNAL(currentIndexChanged(QString)), this, SLOT(setStatus()));

    connect(ClientHandler::clientHandlerInstance(), SIGNAL(messageReady()), this, SLOT(checkWindowStatus()));

    connect(m_ui->listWidget, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(oneWindowPerBuddy()));

    connect(m_ui->removeContact, SIGNAL(clicked()), this, SLOT(clickedRemoveContact()));

    connect(ClientHandler::clientHandlerInstance(), SIGNAL(rosterReceived()), this, SLOT(populateList()));

    connect(ClientHandler::clientHandlerInstance(), SIGNAL(closedWindow()), this, SLOT(removeWindow()));
        connect(ClientHandler::clientHandlerInstance(), SIGNAL(statusReceived()), this, SLOT(populateList())); //
}

BuddyList::~BuddyList()
{
    delete m_ui;
}

void BuddyList::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void BuddyList::closeEvent(QCloseEvent *e)
{
    if(okayToClose())
        e->accept();
    else
        e->ignore();
}

bool BuddyList::okayToClose()
{
    QMessageBox::StandardButton ret;
    ret = QMessageBox::warning(this, tr("Warning"),
                               tr("MyChat is about to close.\n"
                                  "Would you like to contuine?"),
                               QMessageBox::Yes | QMessageBox::Cancel);

    if (ret == QMessageBox::Yes){
        return true;
    }
    else if (ret == QMessageBox::Cancel){
        return false;
    }

    return false;
}
//

void BuddyList::popUp()
{
    ChatWindow *conversationWindow_p = new ChatWindow(this);
    QString contact = m_ui->listWidget->currentItem()->text();
    QString chatWinHeader = "Chat with " + contact;
    ClientHandler::clientHandlerInstance()->setTo(contact);
    conversationWindow_p->nameOfContact = contact;
    conversationWindow_p->setWindowTitle(chatWinHeader);
    conversationWindow_p->show();
    openWindows.push_back(conversationWindow_p);
}

// only one chat window can be opened per contact from buddylist
void BuddyList::oneWindowPerBuddy()
{
    
    if(openWindows.size()!=0){
        if(windowAlreadyOpen() == 0)
        {
            qDebug() << "windows open ";
            popUp();
        }
    }//end of for loop

    else if(openWindows.size()==0)
        popUp();
}

//check if window is already in vector
bool BuddyList::windowAlreadyOpen()
{
    for (int i=0; i<openWindows.size(); i++){

        if(QString::compare(m_ui->listWidget->currentItem()->text(),openWindows.at(i)->nameOfContact)==0)
        {
            qDebug() << "allready open ";
            return true;
        }

    }
    return false;

}
void BuddyList::populateList()
{
    //get contact's list of buddies
    //check who is online
    //populate list
    //addItem()
    for(int i=0; i< m_ui->listWidget->count(); i++)
        m_ui->listWidget->takeItem(i);
    for(int i=0; i<ClientHandler::clientHandlerInstance()->allMyBuddies.size(); i++)
        m_ui->listWidget->addItem(ClientHandler::clientHandlerInstance()->allMyBuddies.at(i));

    m_ui->listWidget->addItem("maurizio");
    m_ui->listWidget->addItem("anthony");
    m_ui->listWidget->addItem("scott");

   // for(int i=0; i<ClientHandler::clientHandlerInstance()->allMyBuddies.size(); i++){
    //    m_ui->listWidget->addItem(ClientHandler::clientHandlerInstance()->allMyBuddies.at(i));
      //  QString temp =  ClientHandler::clientHandlerInstance()->allMyBuddies.at(i) +  " - status!";
   //    // m_ui->listWidget->insertItem(i, temp);
   // }

    return;
}

void BuddyList::checkWindowStatus()
{    
    qDebug() << "Number of windows:" << openWindows.size();
    if(openWindows.size()!=0){

        if (incomingAlreadyOpen()==0)
        {
            qDebug() <<"DOooooooooooooBeeeeeeeeeDoooooBeeeDooo";
            newChatDialog();
        }
        else
            qDebug() << "incomingAlreadyOpen != 0";
    }
    else if (openWindows.size()==0) {
        newChatDialog();
    }// end of outter if else statement

}

void BuddyList::newChatDialog()
{
    ChatWindow *conversationWindow_p = new ChatWindow(this);
    QString contact = ClientHandler::clientHandlerInstance()->getFrom();
    QString chatWinHeader = "Chat with " + contact;
    conversationWindow_p->nameOfContact = contact;
    conversationWindow_p->setWindowTitle(chatWinHeader);
    conversationWindow_p->show();
    openWindows.push_back(conversationWindow_p);
    if(openWindows.size() < 0)
    {
        qDebug() << "Did not push window";
    }
    else
        qDebug() << "Push window sucessful";
    ClientHandler::clientHandlerInstance()->emitPrintingSignal();
}

bool BuddyList::incomingAlreadyOpen()
{
    for (int i=0; i<openWindows.size(); i++){

        if((QString::compare( ClientHandler::clientHandlerInstance()->getFrom(), ClientHandler::clientHandlerInstance()->getUsername(), Qt::CaseSensitive)==0  &&
            QString::compare( ClientHandler::clientHandlerInstance()->getTo(), openWindows.at(i)->nameOfContact, Qt::CaseSensitive)==0) ||
           (QString::compare( ClientHandler::clientHandlerInstance()->getTo(), ClientHandler::clientHandlerInstance()->getUsername(), Qt::CaseSensitive)==0  &&
            QString::compare( ClientHandler::clientHandlerInstance()->getFrom(), openWindows.at(i)->nameOfContact, Qt::CaseSensitive)==0))
        {
            qDebug() << "incoming Chat is Open";
            openWindows.at(i)->showNormal();
            ClientHandler::clientHandlerInstance()->emitPrintingSignal();
            return true;
        }
    }
    return false;

}

void BuddyList::removeWindow()
{
    qDebug() << "This is the number of windows open before closing " <<  openWindows.size();
    for (int i=0; i<openWindows.size(); i++) {
        if (QString::compare( ClientHandler::clientHandlerInstance()->getClosedWindow(), openWindows.at(i)->nameOfContact, Qt::CaseSensitive)==0)
            openWindows.remove(i);
    }
    qDebug() << "This is the number of windows open aftera closing " <<  openWindows.size();
    return;
}

void BuddyList::clickedAddContact()
{
    addContact* AddContactWindow_p = new addContact(this);
    AddContactWindow_p->show();

}

void BuddyList::clickedRemoveContact()
{
//    QListWidgetItem *item = m_ui->listWidget->curcurrentItem();
//    ClientHandler::clientHandlerInstance()->setUsername(userName);
//    //ClientHandler::clientHandlerInstance()->setTo(m_ui->listWidget->itemClicked(allMyBuddies.remove()));
//    ClientHandler::clientHandlerInstance()->setRemove(*item);
//    //ClientHandler::clientHandlerInstance()->setTo(ClientHandler::clientHandlerInstance()->allMyBuddies.remove(
//    ClientHandler::clientHandlerInstance()->sendRemoveContact();
}



void BuddyList::setStatus()
{
    ClientHandler::clientHandlerInstance()->setPresence(status);
    ClientHandler::clientHandlerInstance()->setPresence(m_ui->statusBox->currentText());
    qDebug() << ClientHandler::clientHandlerInstance()->getPresence();
    ClientHandler::clientHandlerInstance()->sendPresence();
}
